package com.hruiworks.campusgroup.utils;

import com.hruiworks.campusgroup.enums.ErrorCode;
import com.hruiworks.campusgroup.exception.BusinessException;
import com.hruiworks.campusgroup.pojo.entity.Administrator;
import com.hruiworks.campusgroup.pojo.entity.User;

import javax.servlet.http.HttpServletRequest;

import java.util.Objects;

import static com.hruiworks.campusgroup.constants.AdministratorConstant.ADMINISTRATOR_ID;
import static com.hruiworks.campusgroup.constants.AdministratorConstant.ADMINISTRATOR_INFO;
import static com.hruiworks.campusgroup.constants.UserConstant.USER_ID;
import static com.hruiworks.campusgroup.constants.UserConstant.USER_INFO;

public class AuthorityUtils {

    /**
     * 获取当前登录用户的userId
     *
     * @param httpServletRequest 请求体
     * @return 返回用户Id
     *
     */
    @Deprecated
    public static Long currentUserId(HttpServletRequest httpServletRequest) {
        Long userId = (Long) httpServletRequest.getAttribute(USER_ID);
        if (Objects.isNull(userId)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "userId为null，检验代码");
        }
        return userId;
    }

    /**
     * 获取当前登录用户的userInfo
     *
     * @param httpServletRequest 请求体
     * @return 返回用户Id
     */
    public static User currentUser(HttpServletRequest httpServletRequest) {
        User user = (User) httpServletRequest.getAttribute(USER_INFO);
        if (Objects.isNull(user)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "user为null，检验代码");
        }
        return user;
    }

    /**
     * 获取当前登录管理员的id
     *
     * @param httpServletRequest 请求体
     * @return 返回管理员id
     */
    public static Long currentAdministratorId(HttpServletRequest httpServletRequest) {
        Long administratorId = (Long) httpServletRequest.getAttribute(ADMINISTRATOR_ID);
        if (Objects.isNull(administratorId)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "administratorId为null，检验代码");
        }
        return administratorId;
    }

    /**
     * 获取当前登录管理员的id
     *
     * @param httpServletRequest 请求体
     * @return 返回管理员id
     */
    public static Administrator currentAdministrator(HttpServletRequest httpServletRequest) {
        Administrator administrator = (Administrator) httpServletRequest.getAttribute(ADMINISTRATOR_INFO);
        if (Objects.isNull(administrator)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "administrator为null，检验代码");
        }
        return administrator;
    }
}
